//
//  AppDelegate.m
//  KoreaFlower
//
//  Created by Nicejinux on 12. 11. 10..
//  Copyright (c) 2012년 Nicejinux. All rights reserved.
//

#import "AppDelegate.h"
#import "ListViewController.h"
#import "FlowerViewController.h"
#import "StreamViewController.h"
#import "WishViewController.h"
#import "RecommandViewController.h"
#import "CategoryViewController.h"
#import "ShopViewController.h"

#import "StreamViewController.h"
#import "GlobalDefine.h"
#import "JSONKit.h"
#import "ListCommunicator.h"



@implementation AppDelegate
{
    UIImage *defaultImg;
}


@synthesize window = _window;
@synthesize tabBarController = _tabBarController;

@synthesize viewController0;
@synthesize viewController1;
@synthesize viewController2;
@synthesize viewController3;
@synthesize viewController4;

@synthesize naviController0;
@synthesize naviController1;
@synthesize naviController2;
@synthesize naviController3;
@synthesize naviController4;

@synthesize flowerListArray;
@synthesize flowerDic;
@synthesize introReq;
@synthesize indicatorView;
@synthesize indicator;
@synthesize internetReach;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor blackColor];
    
    [application setStatusBarStyle:UIStatusBarStyleBlackOpaque];

    UIImage *introImg;
    if(IS_IPHONE_5) {
        introImg = [[UIImage alloc] initWithContentsOfFile:
                    [[NSBundle mainBundle] pathForResource:@"Default-568h@2x" ofType:@"png"]];
    }
    else {
        introImg = [[UIImage alloc] initWithContentsOfFile:
                    [[NSBundle mainBundle] pathForResource:@"Default" ofType:@"png"]];
    }
    
    internetReach = [Reachability reachabilityForInternetConnection];
    [internetReach startNotifier];
    
    UIImageView *introImgView = [[UIImageView alloc] initWithImage:introImg];
    [introImgView setTag:INTRO_IMGVIEW_TAG];
    [self.window addSubview:introImgView];

    CGRect rect = CGRectMake((320-37)/2, ([[UIScreen mainScreen] bounds].size.height)/2+50, 37, 37);
    indicator = [[UIActivityIndicatorView alloc] initWithFrame:rect];
    indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    [introImgView addSubview:indicator];
    [indicator startAnimating];

//    CGRect rect = CGRectMake((320-44)/2, ([[UIScreen mainScreen] bounds].size.height)/2+50, 44, 44);
//    indicatorView = [[LoadingView alloc] initWithFrame:rect];
//    [introImgView addSubview:indicatorView];
//    [indicatorView startAnimating];
    
    //[NSThread sleepForTimeInterval:1];
    [ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]];
    [self setNaviController];
    [self setTabBar];
    [self getFlowerList];
    
    UIImage *tabBarButtonBackground = [[UIImage imageNamed:@"tabBg_em"] stretchableImageWithLeftCapWidth:1 topCapHeight:25];

    [[UITabBar appearance] setBackgroundImage:tabBarButtonBackground];
    [[UITabBar appearance] setSelectedImageTintColor:[UIColor colorWithRed:72.0/255.0 green:169.0/255.0 blue:49.0/255.0 alpha:1.0]];
    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void) getFlowerList
{
    if (introReq) {
        return;
    }
    
    NSString *requestUrl = [NSString stringWithFormat:@"%@", GET_FLOWER_INFO_JSON];
    introReq = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:requestUrl]];
    [introReq setDelegate:self];
    
    [introReq startAsynchronous];
}

- (BOOL)checkData
{
    BOOL canStart = YES;
    
    // DB 에서 데이터 체크. 시작 가능하면 YES, 시작 불가면 NO
    
    return canStart;
}

- (void)readyToStart
{
    UIView *introView = [self.window viewWithTag:INTRO_IMGVIEW_TAG];
    [indicator stopAnimating];
//    [indicatorView stopAnimating];
    [introView removeFromSuperview];
}

- (void)failToStart
{
    // DB에 데이터가 없으면 App종료. 데이터가 있으면 Alert 메시지띄운 후 시작
    if ([self checkData]) {
        //alert 보여주기
        [self readyToStart];
    }
    else
    {
        // App 종료
    }
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    int responseStatusCode = [request responseStatusCode];
    BOOL isSuccess = (responseStatusCode >= 200 && responseStatusCode < 300) ? YES : NO;

    if (isSuccess) {
        flowerDic = [[request responseString] objectFromJSONString];
        NSLog(@"%@", flowerDic);
        
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:[[[flowerDic objectForKey:@"cdnInfo"] objectAtIndex:0] objectForKey:@"cdnPathName"] forKey:@"cdn0"];
        [ud setObject:[[[flowerDic objectForKey:@"cdnInfo"] objectAtIndex:1] objectForKey:@"cdnPathName"] forKey:@"cdn1"];
        [ud synchronize];
        
        [[ListCommunicator sharedInstance] storeCDNListToDB:flowerDic];
        [[ListCommunicator sharedInstance] storeFlowerListToDB:flowerDic];
        
        [self.viewController1 reloadTableData:0];
        [self readyToStart];
    }
    else
    {
        [self failToStart];
    }
}

- (void) setCategoryView
{
    self.window.rootViewController = self.viewController0;
}

- (void) setTabbarHidden:(BOOL)hide
{
    self.viewController1.tabBarController.tabBar.hidden = hide;
    self.viewController2.tabBarController.tabBar.hidden = hide;
    self.viewController3.tabBarController.tabBar.hidden = hide;
    self.viewController4.tabBarController.tabBar.hidden = hide;
    self.tabBarController.tabBar.hidden = hide;
    
    if (hide)
        self.tabBarController.view.frame = CGRectMake(0, 480, self.tabBarController.view.frame.size.width, self.tabBarController.view.frame.size.height);
    else
        self.tabBarController.view.frame = CGRectMake(0, 480 - self.tabBarController.view.frame.size.height, self.tabBarController.view.frame.size.width, self.tabBarController.view.frame.size.height);
}

- (void) setTabBar
{
    self.tabBarController = [[TabbarViewController alloc] init];
    self.window.rootViewController = self.tabBarController;
    self.tabBarController.viewControllers = [NSArray arrayWithObjects:naviController1, naviController2, naviController3, naviController4, nil];
}

- (void) setNaviController
{
    self.viewController0 = [[CategoryViewController alloc]  initWithNibName:@"CategoryViewController"  bundle:nil];
    
    // 탭바 컨트롤러는 여려개의 컨트롤러를 가질 수 있으나, 뷰 혹은 네비게이션 바 등은 가질 수 없다.
    // 즉 네비게이션(push/pop)을 사용하기 위해서는 네비게이션 컨트롤러를 탭바에 넣어야 하고,
    // 뷰 를 사용하기 위해서는 뷰 컨트롤러를 탭바에 넣어야 한다.
    // 여기서 사용되어질 뷰들은 상단에 네비게이션 기능이 있어야 하므로
    // 뷰컨트롤러를 네비게이션 컨트롤러에 먼저 넣고, 그 네비게이션 컨트롤러를 다시 탭바에 넣어야 한다.
    
    self.viewController1 = [[FlowerViewController alloc]  initWithNibName:@"FlowerViewController"  bundle:nil];
    self.naviController1 = [[UINavigationController alloc] initWithRootViewController:self.viewController1];
    self.naviController1.navigationBar.topItem.title = @"전체보기";
    
    if ([self.naviController1.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        UIImage *image = [UIImage imageNamed:@"naviImage"];
        [self.naviController1.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    }
    
    self.viewController2 = [[RecommandViewController alloc] initWithNibName:@"RecommandViewController" bundle:nil];
    self.naviController2 = [[UINavigationController alloc] initWithRootViewController:self.viewController2];
    self.naviController2.navigationBar.topItem.title = @"추천상품";
    
    if ([self.naviController2.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        UIImage *image = [UIImage imageNamed:@"naviImage"];
        [self.naviController2.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    }
    
    self.viewController3 = [[WishViewController alloc]  initWithNibName:@"WishViewController"  bundle:nil];
    self.naviController3 = [[UINavigationController alloc] initWithRootViewController:self.viewController3];
    self.naviController3.navigationBar.topItem.title = @"찜한목록";
    
    if ([self.naviController3.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        UIImage *image = [UIImage imageNamed:@"naviImage"];
        [self.naviController3.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    }
    
    self.viewController4 = [[ShopViewController alloc]  initWithNibName:@"ShopViewController"  bundle:nil];
    self.naviController4 = [[UINavigationController alloc] initWithRootViewController:self.viewController4];
    self.naviController4.navigationBar.topItem.title = @"한국화원";
    
    if ([self.naviController4.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        UIImage *image = [UIImage imageNamed:@"naviImage"];
        [naviController4.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[ASIDownloadCache sharedCache] clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    NSLog(@"didReceiveMemoryWarning %s", __func__);
    [[ASIDownloadCache sharedCache] clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
}

@end
